import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'

declare var $: any
declare var echarts: any
declare var Viewer: any
@Component({
  selector: 'sa-fault-outsource',
  templateUrl: './fault-outsource.component.html',
  styleUrls: ['./fault-outsource.component.css']
})
export class FaultOutsourceComponent implements OnInit {
  factoryvalidatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      companyName: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择公司名称'
          }
          // remote: {
          // 	message: '此厂区限制已存在，请重新添加!',
          //     url: config.BaseURL+"factoryLimit/validateCompanyId.html",
          //     data: function(validator) {
          //         return {
          //             companyId : $("#selectCompanyName").val()
          //         };
          //     },
          // }
        }
      },
      selfTimeInputId: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择时间段'
          }
        }
      }
    }
  }
  fromType: any = ''
  tableData = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  searchKey: string = '' //搜索keyword
  btnData: any = []
  resourceAdd: boolean = false
  resourceEdit: boolean = false
  resourceDeleteBatch: boolean = false
  faultTypeName: string = '' //查询故障类型参数
  isPush: string = '' //是否推送
  selectedCompanyName: string = '' //查询公司参数
  selectedCompanyId: string = '' //查询公司参数
  deviceId: string = '' //查询设备参数
  carNumber: string = '' //查询车牌号码参数
  userList: any = [] //用户数据List
  userName: string = '' //查询用户参数
  userId: string = '' //查询用户id参数
  startTime = '' //查询开始时间参数
  endTime = '' //查询结束时间参数
  dateType: string = '1' //时间类型
  sortType: string = '2' //时间类型
  useTypeL1: string = '' //车辆分类一级
  useTypeL2: string = '' //车辆分类二级
  companyData: any = {} // 和子组件通信的数据
  faultPhenomenon: any = '' //故障现象
  repairContent: any = '' //维修内容
  allChecked: boolean = false //table全选状态值
  selected: any[] = [] //row选择的数据
  rowId: string = '' //批量进厂限制
  lgisPush: any = '0' //是否进厂限制 默认不限制
  isPushTime: number = 6
  isPushTimeFlag: string = ''
  faultTypeArr: any = [
    {
      type: 1,
      text: '传感器'
    },
    {
      type: 2,
      text: 'GPS'
    },
    {
      type: 3,
      text: '线材'
    },
    {
      type: 4,
      text: '主机'
    },
    {
      type: 5,
      text: '其他'
    }
  ]
  waitingRepairCarTopList: any = [] //待维修统计排名
  topNumber: string = '10' //默认top10
  curBtn: string = '' //排名高亮按钮;默认一周
  topTimeID: any = {
    picker1: 'datetimepicker5',
    picker2: 'datetimepicker6'
  } //排名试驾元素ID
  topStartTime: string = '' //排名开始时间
  topEndTime: string = '' //排名结束时间
  modal: any = {
    //图片弹窗
    picture: '',
    active: '', //激活的图片
    activeNum: null //激活的图片下标
  }
  inputCompanyTreeCarData: any = {} //车辆运行状态模块跳转该页面传递过来的参数
  // 设置厂区在线的参数
  onlineSetCompanyId: string = '' // 公司
  onlineSetCompanyName: string = '' // 公司
  factoryOnlinePageSize: number = 10 // 厂区在线表的页的条数
  factoryOnlineCurPage: any = 1 // 当前页码
  factoryOnlinetotalCount: number = 0 // 分页总条数
  factoryOnlineSearchKey: string = '' // 关键字搜素
  factoryOnlineTableData: any = [] // 厂区设置在线的表单数据
  selfTimeInputId: string = '' //自定义时间段input的id值
  selfTimeData: any = [] //自定义时间段时间校验缓存集合
  startTimeSelected: number
  endTimeSelected: number
  difValue: number
  timeSlot: string = '' //提交的时间段
  hourList = [
    {
      index: 0
    },
    {
      index: 1
    },
    {
      index: 2
    },
    {
      index: 3
    },
    {
      index: 4
    },
    {
      index: 5
    },
    {
      index: 6
    },
    {
      index: 7
    },
    {
      index: 8
    },
    {
      index: 9
    },
    {
      index: 10
    },
    {
      index: 11
    },
    {
      index: 12
    },
    {
      index: 13
    },
    {
      index: 14
    },
    {
      index: 15
    },
    {
      index: 16
    },
    {
      index: 17
    },
    {
      index: 18
    },
    {
      index: 19
    },
    {
      index: 20
    },
    {
      index: 21
    },
    {
      index: 22
    },
    {
      index: 23
    }
  ]
  jumpData: any // 跳转页面接收到的数据
  carDeatailUseList = carTypeListObj.carDeatailUseList
  //  initDateRange: any = {}// 时间组件需要渲染的值
  companyParentList: any = [] //公司树的存储值
  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage == undefined ? 1 : queryParams.nowPage
      this.inputCompanyTreeCarData = JSON.parse(common.getCookie('jumpRepairedDeviceList'))
      if (common.getCookie('jumpTo/device-management/fault')) {
        this.jumpData = JSON.parse(common.getCookie('jumpTo/device-management/fault'))
        this.companyData.companyId = this.selectedCompanyId = this.jumpData.companyId
        this.companyData.companyName = this.selectedCompanyName = this.jumpData.companyName
      }
    })
  }
  //父级公司树请求
  ngInitCompany() {
    this.jsonApiService.http('company/companytree.html', null).subscribe(data => {
      this.companyParentList = data
    })
  }
  ngOnInit() {
    this.ngInitCompany()
    this.initAllUser().then(() => {
      this.selectUserName()
    })

    this.initBtn()
    this.reviewDate() // 数据的回显
    if (common.getCookie('jumpTo/device-management/fault')) {
      this.initDate().then(() => {
        $('#datetimepicker3').val(this.jumpData.startTime)
        $('#datetimepicker4').val(this.jumpData.endTime) //当前时间
        this.startTime = $('#datetimepicker3').val()
        this.endTime = $('#datetimepicker4').val()
        this.dateType = '2'
        setTimeout(() => {
          this.load()
        }, 100)
      })
      common.clearCookie('jumpTo/device-management/fault')
    } else if (common.getCookie('jumpRepairedDeviceList')) {
      this.searchKey = this.inputCompanyTreeCarData.carNumber
      this.dateType = this.inputCompanyTreeCarData.dateType
      $('#datetimepicker3').val(this.inputCompanyTreeCarData.startTime)
      $('#datetimepicker4').val(this.inputCompanyTreeCarData.endTime) //当前时间
      this.startTime = $('#datetimepicker3').val()
      this.endTime = $('#datetimepicker4').val()
      setTimeout(() => {
        this.load()
      }, 550)
      common.clearCookie('jumpRepairedDeviceList')
    } else {
      this.initDate().then(() => {
        this.load()
      })
    }
  }
  ngOnDestroy() {
    document.onclick = null
  }
  topDateSelect(type) {
    this.curBtn = type
    let curTime = new Date()
    let curDate = common.getTimeDay(curTime)
    let currentMonthDays = new Date().getDate() - 1
    let startTime, endTime
    switch (type) {
      case '1':
        this.startTime = curDate + ' 00:00:00'
        this.endTime = curDate + ' 23:59:59'
        break
      case '2':
        this.startTime = common.getTimeDay(new Date(curTime.getTime() - 3600 * 24 * 1000 * 6)) + ' 00:00:00'
        this.endTime = curDate + ' 23:59:59'
        break
      case '3':
        this.startTime =
          common.getTimeDay(new Date(curTime.getTime() - 3600 * 24 * 1000 * currentMonthDays)) + ' 00:00:00'
        this.endTime = curDate + ' 23:59:59'
        break
      default:
        this.startTime = ''
        this.endTime = ''
        break
    }
    $('#datetimepicker5').val(this.startTime).change()
    $('#datetimepicker6').val(this.endTime).change()
    this.initCarWaitingRepairTop()
  }
  //关闭待维修车辆Top弹窗
  waitingRepairClose(modal) {
    modal.hide()
  }
  //待维修车辆Top排名
  carWaitingRepairTop(modal) {
    modal.show()
    this.curBtn = ''
    this.topNumber = '10'
    this.initCarWaitingRepairTop()
  }
  // 数据导出
  exportData() {
    // 导出的
    this.startTime = $('#datetimepicker3').val()
    this.endTime = $('#datetimepicker4').val()
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        userName: this.userName, //用户名
        // 'dateType': this.dateType,		//时间类型
        sortType: this.sortType,
        startDate: this.startTime, //开始时间
        endDate: this.endTime, //结束时间
        searchKey: this.searchKey, //搜索内容
        companyId: this.selectedCompanyId, //选择的公司ID
        deviceId: this.deviceId, //设备ID
        useTypeL2: this.useTypeL2,
        export: '1',
        faultPhenomenon: this.faultPhenomenon,
        repairContent: this.repairContent
      }
    }
    let timeCheck = common.correctTime(data.parameters, ['sortType', 'export'], ['startDate', 'endDate'])
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    common.exprotDataFile(data, 'gridPager', config.BaseURL + 'deviceOutsource/exportOutsourceDeviceRepairedList.html')
  }
  //排名回调
  topNumberChange() {
    this.initCarWaitingRepairTop()
  }
  //待维修车辆Top排名数据拉取
  initCarWaitingRepairTop() {
    let data = {
      searchKey: this.searchKey,
      companyId: this.selectedCompanyId,
      deviceId: this.deviceId,
      userName: this.userName,
      faultTypeName: this.faultTypeName,
      startDate: this.startTime,
      endDate: this.endTime,
      isPush: this.isPush, //是否推送
      isByAuth: false,
      useTypeL2: this.useTypeL2
    }
    let reqdata = 'param=' + JSON.stringify(data) + '&topNumber=' + this.topNumber
    this.jsonApiService.http('deviceRepaired/countDataRecordForTop.html', reqdata).subscribe(result => {
      if (result.data && result.success) {
        this.waitingRepairCarTopList = []
        let temArr: any = result.data
        for (let key in temArr) {
          let obj = {
            text: key,
            value: temArr[key]
          }
          this.waitingRepairCarTopList.push(obj)
        }
      }
    })
  }
  //初始化时间
  initDate() {
    var that = this
    return new Promise(function (resolve, reject) {
      System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
        System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
          $('#datetimepicker3')
            .datetimepicker({
              format: 'yyyy-mm-dd hh:ii:ss',
              language: 'zh-CN',
              autoclose: true
            })
            .on('changeDate', function (e) {
              var date = e.date
              var time = common.getTimeMmss(date)
              that.startTime = time
              $('#datetimepicker4').datetimepicker('setStartDate', time)
            })
          $('#datetimepicker4')
            .datetimepicker({
              format: 'yyyy-mm-dd hh:ii:ss',
              language: 'zh-CN',
              autoclose: true
            })
            .on('changeDate', function (e) {
              var date = e.date
              var time = common.getTimeMmss(date)
              that.endTime = time
              $('#datetimepicker3').datetimepicker('setEndDate', time)
            })
          var date = new Date()
          let time1 = common.getTimeMmss(date)
          $('#datetimepicker4').val(time1) //当前时间
          that.endTime = time1
          date.setDate(date.getDate() - 31) //设置前31天
          let time2 = common.getTimeMmss(date)
          $('#datetimepicker3').val(time2)
          that.startTime = time2

          //不良记录的时间
          $('#returnTime')
            .datetimepicker({
              //时间插件
              format: 'yyyy-mm-dd hh:ii:ss',
              language: 'zh-CN',
              autoclose: true
            })
            .on('changeDate', function (e) {
              var date = e.date
              if (!date) {
                return
              }
              var time = common.getTimeMmss(date)
              that.recordDetailFrom.returnTime = time
            })

          $('#returnTime').datetimepicker('setEndDate', date)

          $('#productTime')
            .datetimepicker({
              //时间插件
              format: 'yyyy-mm-dd hh:ii:ss',
              language: 'zh-CN',
              autoclose: true
            })
            .on('changeDate', function (e) {
              var date = e.date
              if (!date) {
                return
              }
              var time = common.getTimeMmss(date)
              that.recordDetailFrom.productTime = time
            })

          $('#productTime').datetimepicker('setEndDate', date)

          resolve()
        })
      })
    })
  }
  // 数据的回显
  reviewDate() {
    // 判断是否需要回显
    var deviceFaultDataString = sessionStorage.getItem('deviceFaultData')
    if (deviceFaultDataString) {
      var deviceFaultData = JSON.parse(deviceFaultDataString)
      this.companyData = deviceFaultData
      this.selectedCompanyId = deviceFaultData['companyId']
      this.selectedCompanyName = deviceFaultData['companyName']
      this.deviceId = deviceFaultData['deviceId']
      this.carNumber = deviceFaultData['carNumber']
      this.useTypeL2 = deviceFaultData['useTypeL2']
      this.useTypeL1 = deviceFaultData['useTypeL1']
      this.userName = deviceFaultData['userName']
      this.userId = deviceFaultData['userId']
      this.faultTypeName = deviceFaultData['faultTypeName']
      this.isPush = deviceFaultData['isPush']
      this.dateType = deviceFaultData['dateType']
      this.sortType = deviceFaultData['sortType']
      this.startTime = deviceFaultData['startTime']
      this.endTime = deviceFaultData['endTime']
      $('#userNameSelect2').val(this.userName).trigger('change')
      $('#datetimepicker3').val(this.startTime)
      $('#datetimepicker4').val(this.endTime)
      sessionStorage.removeItem('deviceFaultData')
    }
  }
  //删除所选时间
  del_date() {
    this.startTime = ''
    this.endTime = ''
    $('#datetimepicker3').val('').change()
    $('#datetimepicker4').val('').change()
    $('#datetimepicker4').datetimepicker('setStartDate', null)
    $('#datetimepicker3').datetimepicker('setEndDate', null)
  }
  //擦除用户所选值
  delUserName() {
    this.userName = ''
    this.userId = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#userNameSelect2').val('')
    $('#select2-userNameSelect2-container').empty()
    $('#select2-userNameSelect2-container').attr('title', '')
    $('#select2-userNameSelect2-container').prepend(str)
  }
  //初始化select2 选项
  selectUserName() {
    var that = this
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        $('#userNameSelect2')
          .select2({
            language: 'zh-CN',
            placeholder: '请选择',
            allowClear: true,
            data: this.userList, //为Select添加数据
            templateResult: this.formatRepo
          })
          .on('select2:select', function (e) {
            var data = e.params.data
            that.userName = data.text
            that.userId = data.id
          })

        //获取推送APP 推送人
        $('#pushUserNameSelect2')
          .select2({
            language: 'zh-CN',
            placeholder: '请选择',
            allowClear: true,
            data: this.userList, //为Select添加数据
            templateResult: this.formatRepo
          })
          .on('select2:select', function (e) {
            var data = e.params.data
            that.pushUserName = data.text
            that.pushName = data.userName
          })
      })
    })
  }
  //select2 格式回调函数
  formatRepo(state) {
    if (!state.id) {
      return state.text
    }
    var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>')
    return $state
  }
  //拉取
  initAllUser() {
    var that = this
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('user/getAllUserList.html', null).subscribe(data => {
        if (data.success) {
          var userList = data.data
          var selectdata = []
          for (var i = 0; i < userList.length; i++) {
            var obj = {
              id: userList[i].id,
              text: userList[i].name,
              userName: userList[i].userName
            }
            selectdata[i] = obj
          }
        }
        that.userList = selectdata
        resolve()
      })
    })
  }
  //table刷新
  refresh() {
    this.load()
  }
  //初始化权限按钮
  initBtn() {
    this.btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_device-management:fault')))
    if (!this.btnData) {
      return
    }
    for (let item of this.btnData) {
      if (item.sourceKey === 'equipmentFailure:add' && item.parentId) {
        this.resourceAdd = true
      }
      if (item.sourceKey === 'equipmentFailure:edit' && item.parentId) {
        this.resourceEdit = true
      }
      if (item.sourceKey === 'equipmentFailure:del' && item.parentId) {
        this.resourceDeleteBatch = true
      }
    }
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    this.searchKey = common.stringTrim(this.searchKey)
    this.load()
  }
  //初始化加载list数据
  load() {
    this.startTime = $('#datetimepicker3').val()
    this.endTime = $('#datetimepicker4').val()
    this.selected = []
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        // dateType: this.dateType,
        sortType: this.sortType,
        searchKey: this.searchKey,
        companyId: this.selectedCompanyId,
        deviceId: this.deviceId,
        userName: this.userName,
        startDate: this.startTime,
        endDate: this.endTime,
        useTypeL2: this.useTypeL2,
        faultPhenomenon: this.faultPhenomenon,
        repairContent: this.repairContent
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('deviceOutsource/findOutsourceRepairedList.html', reqdata).subscribe(result => {
      this.tableData = result.exhibitDatas || []
      let currentTime = new Date()
      for (var i = 0; i < result.exhibitDatas.length; i++) {
        if (result.exhibitDatas[i].createTime && result.exhibitDatas[i].repairedTime) {
          var d1 = result.exhibitDatas[i].createTime.replace(/\-/g, '/')
          var date1 = new Date(d1)
          var d2 = result.exhibitDatas[i].repairedTime.replace(/\-/g, '/')
          var date2 = new Date(d2)
          var s1 = date1.getTime(),
            s2 = date2.getTime()
          var resTime = common.secondToDate((s2 - s1) / 1000)
          this.tableData[i].responseTime = resTime
        }
        result.exhibitDatas[i].restrictTimeFlag = false
        if (result.exhibitDatas[i].restrictTime) {
          if (
            common.mmsstoTimestamp(common.getNowTime()) - common.mmsstoTimestamp(result.exhibitDatas[i].restrictTime) <
            0
          ) {
            result.exhibitDatas[i].restrictTimeFlag = true
          }
        }
        result.exhibitDatas[i].useTypeL2 = this.getUseTypeNameL2(result.exhibitDatas[i].useTypeL2)
      }
      // this.tableData = result.exhibitDatas || [];
      this.tableData.map(item => (item.callDuration = common.secondToDate(item.callDuration)))
      this.totalCount = result.recordCount
    })
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  //新建
  new_fault() {
    this.router.navigate(['/device-management/fault/fault-page'], { queryParams: { type: 'new' } })
  }
  // 车辆分类编码转化
  getUseTypeNameL2(key) {
    if (key) {
      return this.carDeatailUseList[key]
    } else {
      return ''
    }
  }
  //编辑页面
  updata_fault(row) {
    // 存储完再跳转路由
    var deviceFaultData = {}
    // 给本地赋值
    deviceFaultData['companyId'] = this.selectedCompanyId // 公司id
    deviceFaultData['companyName'] = this.selectedCompanyName // 公司名字
    deviceFaultData['deviceId'] = this.deviceId //车牌号
    deviceFaultData['carNumber'] = this.carNumber
    deviceFaultData['useTypeL2'] = this.useTypeL2 //车辆分类
    deviceFaultData['useTypeL1'] = this.useTypeL1
    deviceFaultData['userName'] = this.userName //用户信息
    deviceFaultData['userId'] = this.userId
    deviceFaultData['faultTypeName'] = this.faultTypeName // 进厂限制
    deviceFaultData['isPush'] = this.isPush // 故障类型
    deviceFaultData['dateType'] = this.dateType // 时间类型
    deviceFaultData['sortType'] = this.sortType //升序降序
    deviceFaultData['startTime'] = this.startTime // 开始时间
    deviceFaultData['endTime'] = this.endTime // 结束时间
    sessionStorage.setItem('deviceFaultData', JSON.stringify(deviceFaultData))
    this.router.navigate(['/device-management/fault/fault-page'], {
      queryParams: { id: row.id, type: 'edit', nowPage: this.curPage }
    })
  }
  //推送APP
  pushUserName: any = '' //推送人
  pushName: any = '' //英文推送人
  pushUserListId: any = ''
  push_edit(row, modal) {
    this.delPushUserName()
    this.pushUserListId = row.id
    modal.show()
  }
  pushEditModalhide(modal) {
    this.pushUserName = ''
    this.pushName = ''
    this.pushUserListId = ''
    modal.hide()
  }
  pushEditReset(modal) {
    let reqdata = 'id=' + this.pushUserListId + '&userName=' + this.pushName
    this.jsonApiService.http('deviceRepaired/sendMessageToApp.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.load()
        this.pushEditModalhide(modal)
      }
    })
  }
  delPushUserName() {
    this.pushUserName = ''
    this.pushName = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#pushUserNameSelect2').val('')
    $('#select2-pushUserNameSelect2-container').empty()
    $('#select2-pushUserNameSelect2-container').attr('title', '')
    $('#select2-pushUserNameSelect2-container').prepend(str)
  }
  del_fault(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      let reqdata = 'id=' + row.id
      this.jsonApiService.http('deviceRepaired/delDeviceRepairedById.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }
  //公司选中回调
  companySelected(data) {
    // this.selectedCompanyId = data.companyId;
    // this.selectedCompanyName = data.companyName;
    this.deviceId = data.id
    this.carNumber = data.text
    // this.useTypeL2 = data.useTypeL2;
    // this.useTypeL1 = data.useTypeL1;
  }
  beforeImageInfo: any = [] //维修前图片展示
  afterImageInfo: any = [] //维修后图片展示
  imageType: any
  imagesInfo: any = [] //图片展示
  isViewer: boolean = false //默认隐藏
  //显示图片组件
  viewer: any = ''
  //查看照片
  open_img(row, val) {
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
    this.jsonApiService.http_obj('deviceRepairedV2/queryById.html', { id: row.id }).subscribe(data => {
      if (data.success) {
        // 返回的维修后图片列表数据
        this.beforeImageInfo = JSON.parse(JSON.stringify(data.data.beforeImageInfo))
        // 返回的维修前图片列表数据
        this.afterImageInfo = JSON.parse(JSON.stringify(data.data.afterImageInfo))
      } else {
        this.jsonApiService.message(data.message)
      }
    })

    event.stopPropagation()
    val.show()
    // }
  }
  bigImg: any = '' // 放大的图片
  //图片放大
  bigimg(modal, row) {
    // modal.show();
    this.bigImg = row
    if (this.isViewer && $('.viewer-container').length > 0) {
      System.import('assets/js/viewer/viewer.js').then(() => {
        System.import('assets/js/viewer/bootstrap.bundle.min.js').then(() => {
          System.import('assets/js/viewer/viewer.css').then(() => {
            this.showImg()
          })
        })
      })
    } else {
      this.showImg()
    }
  }
  showImg() {
    var that = this
    var imgList = $('.imagesInfo')[0]
    this.viewer = new Viewer(imgList, {
      url: 'src',
      title: function (image) {
        return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')'
      }
    })
    that.isViewer = true
  }
  //图片hover事件
  switch_img(index) {
    this.modal.activeNum = index
    this.modal.active = this.modal.picture[index]
  }
  //pre
  change_img_left() {
    if (this.modal.activeNum) {
      this.modal.activeNum--
      this.modal.active = this.modal.picture[this.modal.activeNum]
    }
  }
  //next
  change_img_right(e) {
    if (this.modal.activeNum < this.modal.picture.length - 1) {
      this.modal.activeNum++
      this.modal.active = this.modal.picture[this.modal.activeNum]
    }
  }
  //关闭图片弹窗
  imgClose(val) {
    val.hide()
  }
  /**
   * 设备维修记录
   */
  isOpenCalendar: boolean = false
  openRepairedRecord(modal) {
    modal.show()
    this.isOpenCalendar = true
  }
  closeRepairedRecord(modal) {
    modal.hide()
    this.isOpenCalendar = false
  }
  /**
   *  echart图
   */
  activeSelected: any
  startTime_chart: string = ''
  endTime_chart: string = ''
  isChartView: boolean = false
  isMapView: boolean = false
  specifyTime: any = {
    startTime: '',
    endTime: ''
  }
  selectedRow: any
  drawTrackArr: any
  //数据查看
  drawAbnormalChart() {
    if (!this.selectedRow) {
      this.jsonApiService.message('先选择需要查看折线图的车辆')
      return
    }
    if (!this.startTime_chart || !this.endTime_chart) {
      this.jsonApiService.message('时间不能为空')
      return
    }
    let timeCheck = common.correctTimeParams(this.startTime_chart, this.endTime_chart, 0)
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    this.lineParamDeal(this.selectedRow)
  }
  checkAbnormal(row: any) {
    if (row.repairedStatus == '0') {
      if (!row.faultTime) {
        this.jsonApiService.message('该设备没有故障时间!')
        return
      }
      let temStartWait = common.mmsstoTimestamp(row.faultTime)
      row.startTime = row.faultTime
      row.endTime = common.getTimeMmss(new Date(temStartWait + 3 * 24 * 3600 * 1000))
    } else if (row.repairedStatus == '1') {
      let temStartFixed = common.mmsstoTimestamp(row.repairedTime)
      row.startTime = common.getTimeMmss(new Date(temStartFixed - 1 * 24 * 3600 * 1000))
      row.endTime = common.getTimeMmss(new Date(temStartFixed + 2 * 24 * 3600 * 1000))
    }
    // row对象新增属性
    this.activeSelected = row.id
    this.startTime_chart = row.startTime
    this.endTime_chart = row.endTime
    this.isChartView = true
    this.specifyTime = {
      startTime: this.startTime_chart,
      endTime: this.endTime_chart
    }
    this.lineParamDeal(row)
  }
  runParent(value) {
    this.drawTrackArr = value
  }
  //折线图时间回调事件
  getSelectChartTime(time) {
    this.startTime_chart = time.startTime
    this.endTime_chart = time.endTime
  }
  showMapView(val) {
    this.isMapView = val
  }
  //获取传感器通道参数
  lineParamDeal(row) {
    let reqdata = 'deviceId=' + row.deviceId
    this.jsonApiService.http('realtime/getRealTimeData.html', reqdata).subscribe(result => {
      if (result.success && result.data) {
        let params = {
          deviceId: row.deviceId,
          startTime: this.startTime_chart,
          endTime: this.endTime_chart,
          coefficient: result.data.coef
        }
        this.selectedRow = params
      }
    })
  }
  closeChart() {
    this.isChartView = false
  }
  /**
   * 统计有故障记录,无故障记录,问题分类部分[注:数据统计]
   */
  totleCount: number //按公司统计:统计所有
  repairCount: number //按公司统计:有故障记录
  waitRepairedCount: number //按公司统计:统计无故障记录
  dataAbnormalCarList: any = [] //问题数据[饼图]
  dataAbnormalCarTotalList: any = [] //问题记录List[table]
  dataAbnormalCarTotal: number //问题总数
  dataRepaireTotalList: any = [] //维修记录List[table]
  //关闭问题分类
  closeQuestionSort(modal) {
    modal.hide()
  }
  //问题分类数据处理
  questionSort(modal) {
    if (!this.selectedCompanyId) {
      this.jsonApiService.message('请选择需要查看的公司!')
      return
    }
    modal.show()
    let data = {
      searchKey: this.searchKey,
      companyId: this.selectedCompanyId,
      deviceId: this.deviceId,
      userName: this.userName,
      faultTypeName: this.faultTypeName,
      dateType: this.dateType,
      sortType: this.sortType,
      startDate: this.startTime,
      endDate: this.endTime,
      isPush: this.isPush, //是否推送
      isByAuth: false,
      useTypeL2: this.useTypeL2
    }
    let reqdata = 'param=' + JSON.stringify(data)
    this.jsonApiService.http('deviceRepaired/countRepairedScale.html', reqdata).subscribe(result => {
      let dataRepaired: any = [] //饼图数据
      this.dataRepaireTotalList = []
      this.totleCount = result.data.totleCount //总数
      this.repairCount = result.data.repairCount //有故障记录
      this.waitRepairedCount = this.totleCount - this.repairCount //无故障记录
      dataRepaired.push({ value: result.data.repairCount, name: '有故障记录[车]' })
      dataRepaired.push({ value: this.waitRepairedCount, name: '无故障记录[车]' })
      this.dataRepaireTotalList.push({ value: result.data.repairCount, name: '有故障记录[车]' })
      this.dataRepaireTotalList.push({ value: this.waitRepairedCount, name: '无故障记录[车]' })
      this.dataRepaireTotalList.push({ value: this.totleCount, name: '合计' })
      this.loadPieChart('总车辆', 'repairedPieChart', dataRepaired, this.totleCount)
    })
    this.jsonApiService.http('deviceRepaired/countDataRecord.html', reqdata).subscribe(result => {
      this.dataAbnormalCarList = []
      this.dataAbnormalCarTotalList = []
      this.dataAbnormalCarTotal = 0
      if (result.data && result.success) {
        let temArr: any = result.data
        for (let key in temArr) {
          let obj = {
            value: temArr[key],
            name: key
          }
          this.dataAbnormalCarList.push(obj)
          this.dataAbnormalCarTotalList.push(obj)
          this.dataAbnormalCarTotal += temArr[key]
        }
        this.dataAbnormalCarTotalList.push({
          value: this.dataAbnormalCarTotal,
          name: '合计'
        })
        this.loadPieChart('问题总数', 'questionPieChart', this.dataAbnormalCarList, this.dataAbnormalCarTotal)
      }
    })
  }
  //饼状图,eleId:元素Id,data渲染的数据
  loadPieChart(name, eleId, data, total) {
    var questionPie = echarts.init(document.getElementById(eleId))
    questionPie.clear()
    var that = this
    var scale = 1
    let temArr = []
    for (let item of data) {
      if (item.value) {
        temArr.push(item)
      }
    }
    var echartData = temArr
    if (echartData.length == 0) {
      return
    }
    var rich = {
      yellow: {
        color: '#49dff0',
        fontSize: 18 * scale,
        padding: [5, 4],
        align: 'center'
      },
      total: {
        color: '#49dff0',
        fontSize: 28 * scale,
        align: 'center'
      },
      white: {
        color: '#fff',
        align: 'center',
        fontSize: 14 * scale,
        padding: [5, 4]
      },
      blue: {
        color: '#ffc72b',
        fontSize: 18 * scale,
        padding: [5, 4],
        align: 'center'
      },
      hr: {
        borderColor: '#0b5263',
        width: '100%',
        borderWidth: 1,
        height: 0
      }
    }
    var option = {
      backgroundColor: '#031f2d',
      title: {
        text: name,
        left: 'center',
        top: '53%',
        padding: [24, 0],
        textStyle: {
          color: '#fff',
          fontSize: 18 * scale,
          align: 'center'
        }
      },
      legend: {
        selectedMode: false,
        formatter: '{total|' + total + '}',
        data: [echartData[0].name],
        left: 'center',
        top: 'center',
        icon: 'none',
        align: 'center',
        textStyle: {
          color: '#fff',
          fontSize: 16 * scale,
          rich: rich
        }
      },
      series: [
        {
          name: name,
          type: 'pie',
          radius: ['42%', '50%'],
          hoverAnimation: false,
          color: [
            '#c23531',
            '#2f4554',
            '#61a0a8',
            '#d48265',
            '#91c7ae',
            '#749f83',
            '#ca8622',
            '#bda29a',
            '#6e7074',
            '#546570',
            '#c4ccd3'
          ],
          label: {
            normal: {
              formatter: function (params, ticket, callback) {
                return (
                  '{white|' +
                  params.name +
                  '}{yellow|' +
                  params.value +
                  '}\n{hr|}\n{blue|' +
                  ((+params.value / total) * 100).toFixed(1) +
                  '%}'
                )
              },
              rich: rich
            }
          },
          labelLine: {
            normal: {
              length: 35 * scale,
              length2: 0,
              lineStyle: {
                color: '#0b5263'
              }
            }
          },
          data: echartData
        }
      ]
    }
    questionPie.setOption(option)
    window.onresize = function () {
      if (questionPie) {
        questionPie.resize()
      }
    }
  }

  /**
   * 单行数据选中事件,仅支持单行选中,不支持多选
   */
  singleRowSelected(row, e, index) {
    if (
      e.target.className.includes('checkbox') ||
      e.target.className.includes('checkbox-flag') ||
      e.target.className.includes('checkbox-td') ||
      e.target.className.includes('checkbox-label')
    ) {
      this.rowSelected(row, e, index)
      return
    }
    for (let item of this.tableData) {
      item['isChecked'] = false
    }
    this.selected = []
    row.isChecked = !row.isChecked
    this.selected.push(row)
    this.rowId = row.id
  }
  //table 全部选中
  allSelected() {
    this.allChecked = !this.allChecked
    if (!this.allChecked) {
      for (let item of this.tableData) {
        item['isChecked'] = false
      }
      this.selected = []
      this.rowId = ''
    } else {
      var temArr = []
      for (let item of this.tableData) {
        item['isChecked'] = true
        temArr.push(item.id)
        this.selected.push(item)
      }
      for (let item of this.selected) {
        temArr.push(item.rowId)
      }
      this.rowId = temArr.join(',')
    }
  }

  //table复选框数据row选中事件回调:处理选中状态和deviceId
  rowSelected(row, e, index) {
    var index = $.inArray(row, this.selected)
    if (index === -1) {
      row.isChecked = true
      this.selected.push(row)
    } else {
      row.isChecked = false
      this.selected.splice(index, 1)
    }
    var temArr = []
    for (let item of this.selected) {
      temArr.push(item.id)
    }
    this.rowId = temArr.join(',') //处理deviceId,与后台接口交互参数
    this.selected.length === this.pageSize ? (this.allChecked = true) : (this.allChecked = false) //判断是否全选状态
  }

  //批量进厂限制
  updata_device(modal) {
    if (this.rowId == '' || this.selected.length == 0) {
      this.jsonApiService.message('请勾选至少一条数据')
      return
    }
    modal.show()
  }

  //确定批量进厂限制
  autoReset(modal) {
    let isPush = this.lgisPush == 'time' ? '0' : this.lgisPush
    let isPushTime = this.lgisPush == 'time' ? this.isPushTime : ''
    let reqdata = {
      ids: this.rowId,
      isPush: isPush,
      time: isPushTime
    }
    //		'ids=' + this.rowId + "&isPush=" + this.lgisPush;
    this.jsonApiService.http_obj('deviceRepaired/enterFactoryLimitBatch.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        modal.hide()
        this.refresh()
        this.selected = []
        this.rowId = ''
        this.lgisPush = '0'
        this.isPushTime = 6
      }
    })
  }
  // 取消限制
  cancelRestrict(row) {
    this.jsonApiService.confirm_message('确定要取消自定义限制[' + row.restrictTime + '后限制]?').then(() => {
      let reqdata = 'id=' + row.id
      this.jsonApiService.http('deviceRepaired/removeRestrictions.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.refresh()
        }
      })
    })
  }
  //取消批量进厂限制
  lgModalhide(modal) {
    modal.hide()
    this.rowId = ''
    this.selected = []
    this.lgisPush = '0'
    this.isPushTime = 6
    for (let item of this.tableData) {
      item['isChecked'] = false
    }
  }
  //自定义限制,校验非空值,默认6小时,不允许为空
  inputChange() {
    this.isPushTime = Math.abs(Math.floor(this.isPushTime))
    if (!this.isPushTime) {
      this.isPushTime = 6
    }
  }
  //批量进厂限制选框change事件
  resetChange(checked, type) {
    //		if(type === 'Y'&&checked){
    //			this.lgisPush = 1;
    //		}else if(type === 'N'&&checked){
    //			this.lgisPush = 0;
    //		}
  }
  /**
   * 设置厂区在线
   */
  // 点击弹出设置厂区在线的弹框
  setFactoryOnline(modal) {
    this.factoryOnlineSearchKey = ''
    //这里还要做加载表单
    this.loadFactoryOnline()
    this.initAllProjectName().then(() => {
      this.selectCompanyName()
    })
    modal.show()
  }
  // 进厂限制设置表单刷新
  factoryTableRefresh() {
    this.loadFactoryOnline()
  }
  //分页回调
  factoryPaginate(e) {
    this.factoryOnlineCurPage = e.page + 1
    this.factoryOnlinePageSize = e.rows
    this.loadFactoryOnline()
  }
  comptyNameList: any
  //擦除用户所选项目名称
  delfactorySetCompany() {
    this.onlineSetCompanyId = ''
    this.onlineSetCompanyName = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#factorySetCompanyId').val('')
    $('#select2-factorySetCompanyId-container').empty()
    $('#select2-factorySetCompanyId-container').attr('title', '')
    $('#select2-factorySetCompanyId-container').prepend(str)
  }
  //初始化项目名称select2 选项
  selectCompanyName() {
    var that = this
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        $('#factorySetCompanyId')
          .select2({
            language: 'zh-CN',
            placeholder: '请选择',
            allowClear: true,
            data: this.comptyNameList //为Select添加数据
          })
          .on('select2:select', function (e) {
            var data = e.params.data
            that.onlineSetCompanyName = data.text
            that.onlineSetCompanyId = data.id
          })
      })
    })
  }
  //拉取项目名称
  initAllProjectName() {
    var that = this
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('project/projectList.html', null).subscribe(data => {
        if (data.success) {
          var userList = data.data
          var selectdata = []
          for (var i = 0; i < userList.length; i++) {
            var obj = {
              id: userList[i].id,
              text: userList[i].projectName
            }
            selectdata[i] = obj
          }
        }
        that.comptyNameList = selectdata
        resolve()
      })
    })
  }
  // 设置厂区在线的公司选择回调
  onlinecompanySelected(data) {
    // 请求验证接口
    this.onlineSetCompanyId = data.companyId
    this.onlineSetCompanyName = data.companyName
  }
  // 搜索进厂限制设置
  factoryOnlineSearch() {
    this.factoryOnlineCurPage = 1
    this.loadFactoryOnline()
  }
  // 加载进厂限制设置表数据
  loadFactoryOnline() {
    let param = {
      pageSize: this.factoryOnlinePageSize,
      nowPage: this.factoryOnlineCurPage,
      parameters: {
        companyId: this.onlineSetCompanyId, // 公司id
        searchKey: this.factoryOnlineSearchKey
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(param)
    this.jsonApiService.http('factoryLimit/list.html', reqdata).subscribe(data => {
      for (let i = 0; i < data.exhibitDatas.length; i++) {
        let periodTime = data.exhibitDatas[i].period
        let endTime = parseInt(periodTime[periodTime.length - 1]) + 1
        data.exhibitDatas[i].periodTime = periodTime[0] + '点-' + endTime + '点'
      }
      this.factoryOnlineTableData = data.exhibitDatas
      this.factoryOnlinetotalCount = data.recordCount
    })
  }
  // 进厂限制设置关键字搜索
  factory_table_search() {
    this.factoryOnlineCurPage = 1
    this.factoryOnlineSearchKey = common.stringTrim(this.factoryOnlineSearchKey)
    this.loadFactoryOnline()
  }
  // 关闭进厂限制设置弹框
  cancelFactoryOnline(modal) {
    modal.hide()
  }
  // 添加厂区的实体对象
  factory: any = {
    companyId: '', //公司id
    companyName: '', //公司名称
    period: '',
    isRepaired: 1,
    isAlarm: 1
  }
  // 添加厂区弹窗
  factoryAdd(modal, type) {
    this.fromType = type
    this.factory = {
      companyId: '', //公司id
      companyName: '', //公司名称
      period: '',
      isRepaired: 1,
      isAlarm: 1
    }
    this.selfTimeInputId = ''
    $('#setFactoryFrom').data('bootstrapValidator').resetForm()
    modal.show()
  }
  // 编辑厂区弹窗
  editFactory(row, modal, type) {
    this.fromType = type
    this.factory = JSON.parse(JSON.stringify(row))
    this.selfTimeInputId = row.periodTime
    modal.show()
  }
  // 公司选中回调
  factorySelected(data) {
    // console.log(data.companyId,"111111111")
    if (data.companyId) {
      if (this.fromType == 'update' && this.factory.companyId != data.companyId) {
        this.checkFactory(data.companyId)
      }
      if (this.fromType == 'new') {
        this.checkFactory(data.companyId)
      }
      this.factory.companyId = data.companyId
      this.factory.companyName = data.companyName
      $('#selectCompanyName').val(this.factory.companyId)
    }
  }
  onclickSelectCompany() {
    $('#s_timePicker').attr('class', 's_timePicker')
  }
  // 关闭弹框
  closeFactory(modal) {
    $('#setFactoryFrom').data('bootstrapValidator').resetForm()
    this.selfTimeInputId = ''
    $('#s_timePicker').attr('class', 's_timePicker')
    modal.hide()
  }
  // 删除厂区
  delFactory(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除').then(() => {
      let reqdata = 'id=' + row.id
      this.jsonApiService.http('factoryLimit/delete.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.loadFactoryOnline()
        }
      })
    })
  }
  // 校验厂区
  checkFactory(data) {
    // console.log(this.factory.companyId, "2222222")
    let reqdata = 'companyId=' + data
    this.jsonApiService.http('factoryLimit/validateCompanyId.html', reqdata).subscribe(data => {
      if (data.message.indexOf('此厂区限制已存在') != -1) {
        this.jsonApiService.message(data.message)
        this.factory.companyName = ''
        this.factory.companyId = ''
        $("input[name='companyName']").val('').change()
      }
    })
  }
  // 添加提交
  addSubmitFactory(modal) {
    $('#setFactoryFrom').bootstrapValidator('validate') //开启验证
    let isValid = $('#setFactoryFrom').data('bootstrapValidator').isValid() //验证是否通过

    if (isValid) {
      this.jsonApiService.http_obj('factoryLimit/add.html', this.factory).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.loadFactoryOnline()
          this.closeFactory(modal)
        }
      })
    }
  }
  // 编辑提交
  editSubmitFactory(modal) {
    $('#setFactoryFrom').bootstrapValidator('validate') //开启验证
    let isValid = $('#setFactoryFrom').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      this.jsonApiService.http_obj('factoryLimit/update.html', this.factory).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          //
          this.loadFactoryOnline()
          this.closeFactory(modal)
        }
      })
    }
  }
  //自定义时间input点击时间回调
  isShowTimer() {
    $('.s_timePicker').toggleClass('s_isActive')
    this.startTimeSelected = null
    this.endTimeSelected = null
  }
  //自定义时间段校验
  validTime(str1, str2) {
    this.selfTimeData = []
    this.factory.period = []
    var hourListLen = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
    //对渲染的数据进行整合,提起始时间和结束时间
    if (str1 == str2) {
      if (str1 === 0) {
        this.selfTimeData = hourListLen.slice(str1, hourListLen.length - 1)
      } else {
        var selfTimeData1 = hourListLen.slice(str1, hourListLen.length)
        var selfTimeData2 = hourListLen.slice(0, str1)
        this.selfTimeData = selfTimeData1.concat(selfTimeData2)
      }
    }
    if (str1 > str2) {
      var selfTimeData3 = hourListLen.slice(str1, hourListLen.length)
      var selfTimeData4 = hourListLen.slice(0, str2)
      this.selfTimeData = selfTimeData3.concat(selfTimeData4)
    }
    if (str1 < str2) {
      this.selfTimeData = hourListLen.slice(str1, str2)
    }

    this.factory.period = this.selfTimeData
  }
  //提交自定义时间picker
  submitTimerSelected() {
    if (this.startTimeSelected === 0 || this.endTimeSelected === 0) {
    } else {
      if (!this.startTimeSelected) {
        this.jsonApiService.message('请选择开始时间')
        return
      } else if (!this.endTimeSelected) {
        this.jsonApiService.message('请选择结束时间')
        return
      }
    }
    this.selfTimeInputId = this.startTimeSelected + '点-' + this.endTimeSelected + '点'
    $('#selfTimeInput').val(this.selfTimeInputId).change()
    $('.s_timePicker').toggleClass('s_isActive')
    this.validTime(this.startTimeSelected, this.endTimeSelected)
  }
  //时间段选定值点击事件回调
  selectedTime(val, type) {
    if (type === 'start') {
      this.startTimeSelected = val
    } else if (type === 'end') {
      this.endTimeSelected = val
    }
  }
  //维修记录
  clickRecord(type) {
    this.factory.isRepaired = type
  }
  //设备警告
  clickWarning(type) {
    this.factory.isAlarm = type
  }
  //删除时间段
  delSelfTime() {
    this.selfTimeInputId = ''
    $('#selfTimeInput').val('').change()
  }

  /* 新增 

		不良记录
		 
	*/
  //新增 操作
  recordDetailFrom: any = {
    id: '',
    returnTime: '',
    carNumber: '',
    companyName: '',
    deviceId: '',
    productNo: '',
    productTime: '',
    hwVersion: '',
    retestResult: '',
    badReasons: '',
    improvementStrategy: '',
    resolutionTime: '',
    principal: '',
    imagePaths: '',
    faultPhenomenon: '',
    relation: 0
  }
  imageInfoList: any = []
  addRecordDetail(modal) {
    for (let key in this.recordDetailFrom) {
      this.recordDetailFrom[key] = ''
    }
    this.recordDetailFrom.relation = 0 //默认是未关联
    this.recordDetailFrom.returnTime = common.getTimeMmss(new Date())
    if (this.selected.length == 0) {
      this.jsonApiService.message('请先选择一条记录来新增')
      return
    }
    if (this.selected.length != 1) {
      this.jsonApiService.message('只能选择一条[已维修]记录来新增')
      return
    }
    if (this.selected[0].repairedStatus != 1) {
      this.jsonApiService.message('只能选择一条[已维修]记录来新增')
      return
    }
    this.recordDetailFrom.carNumber = this.selected[0].carNumber
    this.recordDetailFrom.deviceId = this.selected[0].deviceId
    this.recordDetailFrom.companyName = this.selected[0].companyName
    this.recordDetailFrom.faultPhenomenon = this.selected[0].faultPhenomenon
    this.recordDetailFrom.relation = this.selected[0].id ? 1 : 0 //0 未关联 1已关联

    this.jsonApiService
      .http_obj('deviceRepaired/getDeviceBaseDataV2.html', {
        deviceId: this.selected[0].deviceId,
        repairedTime: this.selected[0].repairedTime ? this.selected[0].repairedTime : ''
      })
      .subscribe(data => {
        if (data.success) {
          this.recordDetailFrom.productNo = data.data.productNo ? data.data.productNo : ''
          this.recordDetailFrom.productTime = data.data.productTime ? data.data.productTime : ''
          this.recordDetailFrom.hwVersion = data.data.hwVersion ? data.data.hwVersion : ''
          modal.show()
        } else {
          this.jsonApiService.message(data.message)
        }
      })
  }
  recordDetailClose(modal) {
    for (let key in this.recordDetailFrom) {
      this.recordDetailFrom[key] = ''
    }
    modal.hide()
  }
  recordDetailSubmit(modal) {
    if (!this.recordDetailFrom.returnTime) {
      this.jsonApiService.message('寄回时间不能为空')
      return
    }
    if (!this.recordDetailFrom.deviceId) {
      this.jsonApiService.message('设备ID不能为空')
      return
    }
    if (!this.recordDetailFrom.faultPhenomenon) {
      this.jsonApiService.message('故障现象不能为空')
      return
    }
    this.recordDetailFrom.imagePaths = this.imageInfoList.join(',')
    let reqdata = JSON.parse(JSON.stringify(this.recordDetailFrom))
    this.jsonApiService.http_obj('deviceRepaired/add.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.load()
        modal.hide()
      }
    })
  }

  fileList: File = null
  //上传多张
  multifileChange(files: FileList) {
    if (this.isViewer2 && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }

    var that = this
    let multfileList = files

    var reqdata = new FormData()
    reqdata.append('describe', '不良记录')
    reqdata.append('businessType', '1')
    // reqdata.append('deviceId', this.page.deviceId);
    reqdata.append('type', '2') //type 1获取相对路径  2获取绝对路径

    for (var i = 0; i < multfileList.length; i++) {
      this.fileList = multfileList[i]
      const isJPG =
        this.fileList.type === 'image/jpeg' || this.fileList.type === 'image/jpg' || this.fileList.type === 'image/png'
      if (!isJPG) {
        this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!')
        return
      }

      reqdata.append('files', multfileList[i])
    }

    that.jsonApiService.form_http('fileUpload/upload.html', reqdata).subscribe(data => {
      if (data.success) {
        for (var i = 0; i < data.data.length; i++) {
          that.imageInfoList.push(data.data[i])
        }
      }
    })

    for (let k = 0; k < $('.up').length; k++) {
      $('.up')[k].value = null
    }
  }
  //删除
  deleteImg(i) {
    this.imageInfoList.splice(i, 1)

    if (this.isViewer2 && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
  }
  bigImg2: any = '' //
  isViewer2: boolean = false //默认隐藏
  bigImgClick(modal, img) {
    // modal.show();
    this.bigImg2 = img
    if (this.isViewer2 && $('.viewer-container').length > 0) {
      System.import('assets/js/viewer/viewer.js').then(() => {
        System.import('assets/js/viewer/bootstrap.bundle.min.js').then(() => {
          System.import('assets/js/viewer/viewer.css').then(() => {
            this.showImg2()
          })
        })
      })
    } else {
      this.showImg2()
    }
  }
  //显示图片组件
  viewer2: any = ''
  showImg2() {
    var that = this
    var imgList = $('.imgFileList')[0]
    this.viewer2 = new Viewer(imgList, {
      url: 'src',
      title: function (image) {
        return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')'
      }
    })
    that.isViewer2 = true
  }

  repairedMonkeyDetail: any = {
    repairOrders: []
  }
  // 维修费用明细
  repairedMonkey(modal, row) {
    let reqdata = 'id=' + row.id
    this.jsonApiService.http2('deviceRepairedV2/getDeviceRepairedV2PriceMsg.html', reqdata).subscribe(data => {
      if (data.success) {
        this.repairedMonkeyDetail = data.data || { repairOrders: [] }
      }
    })
    modal.show()
  }
  closeRepairedMonkey(modal) {
    modal.hide()
  }
}
